import React from 'react'
import NavBar from '../../components/navBar/navBar.jsx'
import {Form,Field,ErrorMessage,withFormik} from 'formik'
import {Toast} from 'antd-mobile'
import {Link} from 'react-router-dom'
import * as Yup from 'yup'
import './login.scss'
import axios from '../../utils/axios.js'
 class Login extends React.Component{

    render(){
        return <div className='login'>
            <NavBar>账号登录</NavBar>
            <Form>
                <Field className='input' name='username' placeholder='请输入账号'></Field>
                <ErrorMessage className='error' name='username' component='div'></ErrorMessage>
                <Field className='input' name='password' placeholder='请输入密码'></Field>
                <ErrorMessage className='error' name='password' component='div'></ErrorMessage>
                <button className='btn' type="submit">登 录</button>
            </Form>
            <Link to='/registe'>还没账号，前往注册</Link>
        </div>
    }
}
Login=withFormik({
    mapPropsToValues:()=>({username:'',password:''}),
    validationSchema:Yup.object().shape({
        username:Yup.string()
                 .required('请输入账号')
                 .matches(/\w{4,8}/,'请输入4到8为字符'),
        password:Yup.string()
                 .required('请输入密码')
                 .matches(/[0-9a-zA-Z]{6}/,'请输入6位数字字母组合')
    }),
    handleSubmit:async(values,{props})=>{
        console.log(values,'999------',props)
        let {username,password}=values
        let res=await axios.post('/user/login',{
            username,password
        })
        if(res.data.status===200){  
            localStorage.setItem('token',res.data.body.token)  
            if(props.location.state){
                console.log(res,props)
                props.history.replace(props.location.state.from.pathname)
            }else{
                props.history.push('/home/my')
            }
            
        }else{
            Toast.info(res.data.description, 1, null, false);
        }
    }
})(Login)

export default Login